package elcom.control.processor;

import java.util.ArrayList;
import java.util.Iterator;

import elcom.model.common.Log;
import elcom.model.data.QueueIO;
import elcom.model.data.Student;

public class Processor extends ThreadNew {
	private QueueIO<Student> queIn = null;
	private QueueIO<String> queOut = null;
	private QueueIO<ThreadNew> queTin = null;
	private ArrayList<Student> lstStudent = new ArrayList<>();
	private ArrayList<String> lstValue = new ArrayList<>();
	private boolean isSuspend = false;
	private int asd = 0;


	public Processor(QueueIO<ThreadNew> queTin, QueueIO<Student> queIn, QueueIO<String> queOut) {
		this.queIn = queIn;
		this.queOut = queOut;
		this.queTin = queTin;
	}

	@Override
	public void run() {
		try {
			while (true) {
				if (!isSuspend)
					addToQueIn();
				if (isSuspend) {
					synchronized (queIn) {
						queIn.wait(20000);
					}
				}
				if (!isSuspend) {
					getData();
					processData();
					sendData();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.logErr(e.toString());
		}
	}

	private void addToQueIn() {
		if (queTin.addD(this)) {
			suspended();
		}
		suspended();
	}

	private void getData() {
		asd++;
		synchronized (queIn) {
			int s = queIn.size();
			s = s / 10;
			int i = 0;
			s = 150;
			Iterator<Student> ite = queIn.iterator();
			while (ite.hasNext()) {
				if (i >= s) {
					break;
				}
				Student student = ite.next();
				lstStudent.add(student);
				i++;
			}
			for (int j = 0; j < lstStudent.size(); j++) {
				Student student = lstStudent.get(j);
				queIn.remove(student);
			}
			Log.logInfo(this.getName() + "*"+ asd +"*" + " getData: " + lstStudent.size());
		}
	}
	
	private void processData(){
		for (int i = 0; i < lstStudent.size(); i++) {
			String value = lstStudent.get(i).toString();
			lstValue.add(value);
		}
		lstStudent.clear();
	}

	private void sendData(){
		synchronized (queOut) {
			for (int i = 0; i < lstValue.size(); i++) {
				String value = lstValue.get(i);
				queOut.addLast(value);
			}
			if (queOut.size() > 200) {
				queOut.notifyAll();
			}
			lstValue.clear();
		}
	}
	
	@Override
	protected void suspended() {
		isSuspend = true;
	}

	@Override
	public synchronized void resumed() {
		isSuspend = false;
//		notifyAll();
	}

}
